<?php
namespace common\action;

use herosphp\bean\Beans;
use herosphp\core\Controller;
use herosphp\core\WebApplication;
use herosphp\http\HttpRequest;
use herosphp\utils\Page;
use herosphp\files\FileUpload;

use herosphp\utils\AjaxResult;

define('COM_ERR_MSG', '(⊙o⊙) 系统出了小差！');

/**
 * 模块通用 Action
 * @author          yangjian<yangjian102621@gmail.com>
 */
abstract class CommonAction extends Controller {

    /**
     * 当前页面
     * @var int
     */
    protected $page = 1;

    /**
     * 没页显示多少条记录
     * @var int
     */
	 protected $pagesize = 15;

    /**
     * 查询条件
     * @var string|array
     */
    protected $conditions;

    /**
     * 排序方式
     * @var string|array
     */
    protected $order;

    /**
     * 分组字段
     * @var string
     */
    protected $group;

    /**
     * 分组条件
     * @var string|array
     */
    protected $having;

    /**
     * 查询字段
     * @var string|array
     */
    protected $fields;

    /**
     * 管理员用户
     * @var array
     */
    protected $loginUser;

    /**
     * Beans服务的key
     * @var string
     */
    protected $serviceBean;

    public function __construct()
    {
        parent::__construct();
        $this->assign("noRecords", "(⊙o⊙)抱歉，没有找到您要的内容.");
        $request = WebApplication::getInstance()->getHttpRequest();
        $module = $request->getModule();
        $action = $request->getAction();
        $saas_url = WebApplication::getInstance()->getconfig('saas_api_url');
        $this->assign("saas_url", $saas_url);
        $this->assign("index_url", url("/{$module}/{$action}/index"));
        $this->assign("insert_url", url("/{$module}/{$action}/insert"));
		$this->assign("add_url", url("/{$module}/{$action}/add"));
		$this->assign("do_add_url",url("/{$module}/{$action}/do_add"));
		$this->assign("do_edit_url",url("/{$module}/{$action}/do_edit"));
        $this->assign("do_delete_url", url("/{$module}/{$action}/do_delete"));

        $this->assign("delete_url", url("/{$module}/{$action}/delete"));

		$this->assign("edit_url", url("/{$module}/{$action}/edit"));
		$this->assign("detail_url", url("/{$module}/{$action}/detail"));
        $this->assign("update_url", url("/{$module}/{$action}/update"));
        $this->assign("upload_url", url("/{$module}/upload/upload"));
		$this->assign("image_search_url", url("/{$module}/upload/image_search"));
		$this->assign("image_list_url", url("/{$module}/upload/image_list"));
		$this->assign("image_show_url", url("/{$module}/upload/image_show"));
		$currentOpt = $request->getModule() . '/' . $request->getAction() . '/' . $request->getMethod();
        $this->assign("module",$module);
        $this->assign("action",$action);
        $this->assign("method",$request->getMethod());
        $this->assign("pro_unit",C("pro_unit"));
        $this->assign("pro_std",C("pro_std"));
		$this->assign('currentOpt',$currentOpt);
    }
    public function do_add(HttpRequest $request)
    {
        return $this->insert($request->getParameter('data'));
    }

    public function do_edit(HttpRequest $request)
    {
        return $this->update($request->getParameter('data'), $request);
    }

    /**
     * 首页列表
     * @param HttpRequest $request
     */
    public function index( HttpRequest $request ) {
		if($request->getParameter('export') == 1){
			$this->setPagesize(999999999);
		}

        $this->page = $request->getParameter('page', 'intval');
        if ( $this->page <=0 ) {
            $this->page = 1;
        }
        $service = Beans::get($this->getServiceBean());
        $total = $service->count($this->getConditions());
        $items = $service->getItems($this->getConditions(), $this->getFields(), $this->getOrder(),
        array($this->getPage(), $this->getPagesize()), $this->getGroup(), $this->getHaving());
        //初始化分页类
        $pageHandler = new Page($total, $this->getPagesize(), $this->getPage(), 4);
		$this->assign('total',$total);

        //获取分页数据
        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE);
        //组合分页HTML代码
        if ( $pageData ) {
            $pagemenu = '<ul class="pagination blog-pagination">';
				$pagemenu .= '<li><a href="'.$pageData['prev'].'">上一页</a></li> ';
            foreach ( $pageData['list'] as $key => $value ) {
                if ( $key == $this->page ) {
                    $pagemenu .= '<li class="active"><a href="#fakelink">'.$key.'</a></li> ';
                } else {
                    $pagemenu .= '<li><a href="'.$value.'">'.$key.'</a></li> ';
                }
            }
			$pagemenu .= '<li><a href="'.$pageData['next'].'">下一页</a></li> ';
            $pagemenu .= '</ul>';
        }

		$this->assign('pagesize', $this->getPagesize());
        $this->assign('pagemenu', $pagemenu);
        $this->assign('items', $items);
		/*if($request->getParameter('export') == 1){
			$filter = $this->getTemplateVar('_filter');
			$excel = array();
			foreach($items as $k => $v)
			{
				$tmp = array();
				foreach($filter as $kk => $vv)
				{
					$tmp[] = $v[$vv];
				}
				$excel[] = $tmp;
			}
			phpexcel($this->getTemplateVar('_table'),$this->getTemplateVar('_header'),$excel);
			exit();
		}*/
		$this->setView(strtolower($request->getAction()) . '/index');
    }

    /**
     * 编辑操作
     * @param HttpRequest $request
     * @return void
     */
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id');
		if ( $id == '' ) {
            $this->showMessage('danger', COM_ERR_MSG);
        } else {
            $conditions = $this -> getTemplateVar('conditions');
            $conditions['id'] = $id;
            $service = Beans::get($this->getServiceBean());
            $item = $service->getItem($conditions);
			$this->assign('id',$id);
            $this->assign('item', $item);

        }
		$this->setView(strtolower($request->getAction()).'/add');
    }

    /**
     * 插入数据
     * @param array $data
     */
    public function insert( $data ) {

        $service = Beans::get($this->getServiceBean());

        if ( $service->add($data) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 更新数据
     * @param array $data
     * @param HttpRequest $request
     */
    public function update( $data, HttpRequest $request ) {

        if ( !$data ) AjaxResult::ajaxFailtureResult();

        $id = $request->getParameter('id');
		if ( $id == "" ) AjaxResult::ajaxResult('error', COM_ERR_MSG);

        $service = Beans::get($this->getServiceBean());
        if ( $service->update($data, $id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }

    }

    /**
     * 快速保存
     * @param HttpRequest $request
     */
    public function quicksave( HttpRequest $request ) {

        $hids = $request->getParameter('hids');
        $datas = $request->getParameter('data');
        $service = Beans::get($this->getServiceBean());
        $counter = 0;
        // 保存数据
        foreach ( $hids as $key => $id ) {
            if ( $service->update($datas[$key], $id) ) {
                $counter++;
            }
        }

        //全部数据保存成功，则该操作成功
        if ( $counter == count($hids) ) {
            AjaxResult::ajaxResult('ok', '保存成功！');
        } else {
            AjaxResult::ajaxResult('error', '保存失败！');
        }
    }

    /**
     * 删除单条数据
     * @param HttpRequest $request
     */
    public function delete( HttpRequest $request ) {

        $id = $request->getParameter('id');
		if ( $id == "" ) AjaxResult::ajaxResult('error', COM_ERR_MSG);
        $service = Beans::get($this->getServiceBean());
        if ( $service->delete($id) ) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 删除多条数据
     * @param HttpRequest $request
     */
    public function deletes( HttpRequest $request ) {

        $ids = $request->getParameter('ids');
        if ( empty($ids) ) AjaxResult::ajaxResult('error', COM_ERR_MSG);
        $service = Beans::get($this->getServiceBean());
		if ( $service->deletes(array('id' => array('$in' => $ids) ))) {
            AjaxResult::ajaxSuccessResult();
        } else {
            AjaxResult::ajaxFailtureResult();
        }
    }

    /**
     * 检验某个字段的值是否在数据库中存在，用于保持某个字段的唯一性
     * @param string $field 字段值
     * @param string $value 字段名
     */
    protected function checkField($field, $value) {

        $value = trim($value);
        $service = Beans::get($this->getServiceBean());
        $exists = $service->getItem(array($field => $value));
        if ( $exists ) {
            AjaxResult::ajaxResult('error', "{$value} 在数据库中已存在，请更换！");
        }

    }

    /**
     * 信息显示模板
     * @param $type 消息类型 info warnning success danger
     * @param $message
     * @param $url
     */
    public function showMessage( $type, $message, $url ) {

        $this->assign('messageType', $type);
        $this->assign('message', $message);
        $this->assign('gotoUrl', $url);
        $this->setView('inc/message');
        //$url = url("/common_message_index/type-{$type}-message-".urlencode($message)."-url-".urlencode($url));
        //$this->location($url);

    }

    /**
     * @param HttpRequest $request
     */
    public function message( HttpRequest $request ) {

        $this->assign('type', $request->getParameter('type'));
        $this->assign('message', $request->getParameter('message', 'urldecode'));
        $this->assign('url', $request->getParameter('url', 'urldecode'));
        $this->setView('unsign_tip');

    }

    /**
     * @param array|string $conditions
     */
    public function setConditions($conditions)
    {
        $this->conditions = $conditions;
    }

    /**
     * @return array|string
     */
    public function getConditions()
    {
        return $this->conditions;
    }

    /**
     * @param array|string $fields
     */
    public function setFields($fields)
    {
        $this->fields = $fields;
    }

    /**
     * @return array|string
     */
    public function getFields()
    {
        return $this->fields;
    }

    /**
     * @param string $group
     */
    public function setGroup($group)
    {
        $this->group = $group;
    }

    /**
     * @return string
     */
    public function getGroup()
    {
        return $this->group;
    }

    /**
     * @param array|string $having
     */
    public function setHaving($having)
    {
        $this->having = $having;
    }

    /**
     * @return array|string
     */
    public function getHaving()
    {
        return $this->having;
    }

    /**
     * @param array|string $order
     */
    public function setOrder($order)
    {
        $this->order = $order;
    }

    /**
     * @return array|string
     */
    public function getOrder()
    {
        return $this->order;
    }

    /**
     * @param int $page
     */
    public function setPage($page)
    {
        $this->page = $page;
    }

    /**
     * @return int
     */
    public function getPage()
    {
        return $this->page;
    }

    /**
     * @param int $pagesize
     */
    public function setPagesize($pagesize)
    {
        $this->pagesize = $pagesize;
    }

    /**
     * @return int
     */
    public function getPagesize()
    {
        return $this->pagesize;
    }

    /**
     * @param string $serviceBean
     */
    public function setServiceBean($serviceBean)
    {
        $this->serviceBean = $serviceBean;
    }
	public function detail(HttpRequest $request)
	{

		$this->edit($request);

		$item = $this->getTemplateVar('item');
		echo json_encode($item);
		exit();;
	}

    /**
     * @return string
     */
    public function getServiceBean()
    {
        return $this->serviceBean;
    }

	public function add(HttpRequest $request){
			
		$this->setView(strtolower($request->getAction()) . '/add');
	}

    public function getPagemenu($page, $pageData){

        $pagemenu = '';

        if ($pageData) {
            $pagemenu = '<ul class="pagination">';
            $pagemenu .= '<li><a href="' . $pageData['prev'] . '" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
            foreach ($pageData['list'] as $key => $value) {
                if ($key - $page > 4) {//省略号
                    $pagemenu .= '<li><a href="javascript:void(0)">...</a></li> ';
                }
                if ($key == $page) {
                    $pagemenu .= '<li class="active"><a href="#fakelink">' . $key . '</a></li> ';
                } else {
                    $pagemenu .= '<li><a href="' . $value . '">' . $key . '</a></li> ';
                }
                if ($page - $key > 4) {//省略号
                    $pagemenu .= '<li><a href="javascript:void(0)">...</a></li> ';
                }
            }
            $pagemenu .= '<li><a href="' . $pageData['next'] . '" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>';
            $pagemenu .= '</ul>';
        }
        return $pagemenu;

    }

    /**
     * 用户中心分页
     * @param $total 数量
     * @return string
     */
    public function memberPagemenu($total){

        //初始化分页类
        $pageHandler = new Page($total, $this->getPagesize(), $this->getPage(), 3);

        //获取分页数据
        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE, false);
        //组合分页HTML代码
        $pagemenu = '';
        if ($pageData) {
            $pagemenu = '<nav class="pageBar">';
            $pagemenu .= '<div class="number">共有' . $total . '条</div>';
            $pagemenu .= '<ul class="list">';

            if($pageData['prev']!="#") {
                $pagemenu .= '<li class="prev"><a href="' . $pageData['prev'] . '"><i></i></a></li>';
            }
            foreach ($pageData['list'] as $key => $value) {
                if ($key - $this->page > 4) {//省略号
                    $pagemenu .= '<li class="li"><a href="javascript:void(0)">...</a></li> ';
                }
                if ($key == $this->page) {
                    $pagemenu .= '<li class="li"><span class="active">' . $key . '</span></li> ';
                } else {
                    $pagemenu .= '<li class="li"><a href="' . $value . '">' . $key . '</a></li> ';
                }
                if ($this->page - $key > 4) {//省略号
                    $pagemenu .= '<li><a href="javascript:void(0)">...</a></li> ';
                }
            }
            if($pageData['next']!="#") {
                $pagemenu .= '<li class="next"><a href="' . $pageData['next'] . '"><i></i></a></li>';
            }
            $pagemenu .= '</ul>';
            $pagemenu .= '</nav>';
        }
        $this->assign('pagemenu', $pagemenu);

    }

    protected function generatePageMenu($total) {

        //初始化分页类
        $pageHandler = new Page($total, $this->getPagesize(), $this->getPage(), 3);

        //获取分页数据
        $pageData = $pageHandler->getPageData(DEFAULT_PAGE_STYLE, true);
        //组合分页HTML代码
        if ( $pageData ) {
            //old
     /*       $pagemenu = '<ul class="pagination">';
            $pagemenu .= '<li class="form-inline"><span>每页：<select class="form-control input-sm" id="per-pagesize">';
            foreach ( getConfig('admin_pagesize_options') as $v ) {
                if ( $v == $this->pagesize ) {
                    $pagemenu .= '<option value="'.$v.'" selected>'.$v.'</option>';
                } else {
                    $pagemenu .= '<option value="'.$v.'">'.$v.'</option>';
                }
            }
            $pagemenu .= '</select> 条</span></li>';
            $pagemenu .= '<li class="disabled"><a href="#">共'.$total.'条</a></li> ';
            $pagemenu .= '<li><a href="'.$pageData['first'].'">首页</a></li> ';
            $pagemenu .= '<li><a href="'.$pageData['prev'].'">上一页</a></li> ';
            foreach ( $pageData['list'] as $key => $value ) {
                if ( $key == $this->page ) {
                    $pagemenu .= '<li class="active"><a href="#fakelink">'.$key.'</a></li> ';
                } else {
                    $pagemenu .= '<li><a href="'.$value.'">'.$key.'</a></li> ';
                }
            }
            $pagemenu.= '<li><a href="'.$pageData['next'].'">下一页</a></li> ';
            $pagemenu .= '<li><a href="'.$pageData['last'].'">尾页</a></li> ';
            $pagemenu .= '</ul>';*/


            //new

            $pagemenu = '<div class="page-bar">';
            $pagemenu .=' <div class="info">共'.$total.'条，每页显示<div class="css-select"><div class="chosen"><span></span><i class="angle-down"></i>';
           $pagemenu .='<input type="hidden" name="pagesize" value="'.$this->pagesize.'"></div><ul id="pageSize">';
            foreach ( getConfig('admin_pagesize_options') as $v ) {
                    $pagemenu .= '<li data-value="'.$v.'">'.$v.'</li>';
            }
            $pagemenu .='</ul></div></div><ul class="bar">';
            $pagemenu .=' <li class="prev"><a href="'.$pageData['prev'].'"><i class="arrow-left ib"></i></a></li>';
            foreach ( $pageData['list'] as $key => $value ) {
                if ( $key == $this->page ) {
                    $pagemenu .= '<li><a href="#fakelink" class="active">'.$key.'</a></li> ';
                } else {
                    $pagemenu .= '<li><a href="'.$value.'">'.$key.'</a></li> ';
                }
            }
            $pagemenu .='<li class="next"><a href="'.$pageData['next'].'"><i class="arrow-right ib"></i></a></li>';
            $pagemenu .=' </ul></div>';


        }

        $this->assign('pagemenu', $pagemenu);

    }

}
